<?php
namespace Todo\Model\Base;

use Todo\Model\BaseModel;
use Todo\Service\DictService;

class StudentModel extends BaseModel
{
    public $tableName = 'base_student';

    public $_validate = array(
        array('name', 'require', '请输入学生姓名'),
        array('name','1,50','姓名长度超出限制！',1,'length'),
        array('number', 'require', '请输入学生学号'),
        array('number','1,20','学号长度超出限制！',1,'length')
    );

    protected $_auto = array(
        array('birthday', '_birthday', self::MODEL_BOTH, 'callback'),
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );

    protected function _birthday(){
        $birthday = I('post.birthday');
        return $birthday ? strtotime($birthday) : 0;
    }

    protected function _before_insert(&$data, $options)
    {
        $User = D('Todo/Sys/User');
        $userInfo = $User->findByField('account', $data['number']);
        if($userInfo) {
            $userId = $userInfo['id'];
        }else{
            $userInfo = array(
                'account' => $data['number'],
                'email'   => $data['email'],
                'phone'   => $data['phone'],
                'nickname'   => $data['name']
            );
            $userId = $User->insert($userInfo);
            if(!$userId) return false;

            $identity = D('Todo/Sys/Identity')->findByField('code', 'student');
            if(!$User->addIdentity($userId, $identity['id'], $data['number'])) return false;
        }
        if($data['class_id']){
            $classInfo = D('Todo/Base/Class')->keyFind($data['class_id']);
            $data['grade'] = $classInfo['grade'];
            $data['system'] = $classInfo['system'];
            $data['depart_id'] = $classInfo['depart_id'];
        }
        $data['user_id'] = $userId;
        return $userId;
    }

    /**
     * 导入一行数据
     * @param $row 数据
     * @param int $exists=1 数据冲突处理方式：1报错，2跳过，3覆盖
     * @return bool
     */
    public function importOne($row, $exists=1){
        if(count($row) < 2 || !$row[0] || !$row[1] || !$row[2]){
            $this->error = "姓名、学号、班级不能为空";
            return false;
        }
        $data = array(
            'name' => $row[0],
            'number' => $row[1]
        );
        $classInfo = D('Todo/Base/Class')->where(array('title'=>$row[2]))->cache(true)->getField('id');//班级
        if(!$classInfo){
            $this->error = "班级(".$row[2].")不存在";
            return false;
        }
        $data['class_id'] =  $classInfo['id'];
        $data['grade'] = $classInfo['grade'];
        $data['system'] = $classInfo['system'];
        $data['depart_id'] = $classInfo['depart_id'];

        if(count($row)>3 && $row[3]) {// 性别
            $data['sex'] = DictService::getInstance()->getDictValue('SEX', $row[3]);
        }else{
            $data['sex'] = '0';
        }
        if(count($row)>4 && $row[4]) $data['email'] = $row[4]; //邮箱
        if(count($row)>5 && $row[5]) $data['phone'] = $row[5]; //电话
        if(count($row)>6 && $row[6]) $data['address'] = $row[6]; //联系地址
        if(count($row)>7 && $row[7]) $data['birthday'] = strtotime($row[7]); //生日
        $old = $this->where(array('number' => $row[1]))->find();
        if($old){ //学号已存在
            if($exists == 1) {
                $this->error = '学号为（'.$row[1].'）的学生信息已经存在';
                return false;
            }else if($exists == 2) return true;
            else{
                $old = array_merge($old, $data);
                return $this->save($old) !== false;
            }
        }else{ //学号不存在
            return $this->insert($data);
        }
    }

    /**
     * 导出Excel
     * @param $list array 数据列表
     * @param $excel ExcelUtil Excel操作对象
     */
    public function exports($list, $excel){
        $title = array(
            'name'=>'姓名',
            'number'=>'学号',
            'class'=>'班级',
            'grade'=>'年级',
            'depart'=>'专业',
            'sex'=>'性别',
            'email'=>'邮箱',
            'phone'=>'手机号',
            'address'=>'联系地址',
            'birthday'=>'生日'
        );
        foreach ($list as &$row){
            if($row['class_id']) {
                $classInfo = D('Todo/Base/Class')->keyFind($row['class_id']);
                $row['class'] = $classInfo['title'];
                $row['grade'] = $classInfo['grade'];
                $row['depart'] = D('Todo/Base/Department')->keyFind($classInfo['depart_id'], 'title');
            }else {
                $row['class'] = '';
                $row['depart'] = '';
                $row['grade'] = '';
            }

            if($row['sex']) $row['sex'] = DictService::getInstance()->getDictTitle('SEX', $row['sex']);
            else $row['sex'] = '';

            if($row['birthday']) $row['birthday'] = date('Y-m-d',$row['birthday']);
            else $row['birthday'] = '';
        }
        $excel->exportExcel("学生", $title, $list);
    }
}